package com.jx.driving.protocol.terminal.codec;

import java.util.Arrays;
import java.util.List;

import com.jx.driving.protocol.terminal.channel.Channel;

public class CodecPipeline implements Codec {

    private List<Codec> codecList;

    public CodecPipeline(Codec... codec) {
	codecList = Arrays.asList(codec);
    }

    @Override
    public Object decode(Channel c, Object in) {
	Object value = in;
	for (Codec codec : codecList) {
	    value = codec.decode(c, value);
	    if (value == null) {
		break;
	    }
	}
	return value;
    }

    @Override
    public Object encode(Channel c, Object in) {
	Object value = in;
	for (int i = codecList.size() - 1; i >= 0; i--) {
	    Codec codec = codecList.get(i);
	    value = codec.encode(c, value);
	    if (value == null) {
		break;
	    }
	}
	return value;
    }

}
